import cv2 as cv
from PIL import ImageGrab
import time
import os

class ImageMatchByCV:
    def find_image(self, template_name, similarity=1):
        #截取当前大图并保存至硬盘
        screen_path = os.path.abspath('') + '\\screenshot\\screen.png'
        ImageGrab.grab().save(screen_path)
        #读取图片
        screen = cv.imread(screen_path)

        #读取模板图片, 并获取其宽高
        template_path = os.path.abspath('') + '\\template\\' + template_name
        template = cv.imread(template_path)
        template_width = template.shape[1]  #shape属性的结果顺序是(高, 宽)
        template_height = template.shape[0]

        #模板匹配计算
        result = cv.matchTemplate(screen, template, cv.TM_CCOEFF_NORMED)
        #  cv.minMaxLoc(result)可以理解为: (最小匹配度,最大匹配度,匹配最糟糕的坐标, 匹配完美的左上顶点坐标)
        similarity1 = cv.minMaxLoc(result)[1]
        start_x, start_y = cv.minMaxLoc(result)[3]
        #计算中心点
        center_x = start_x + int(template_width/2)
        center_y = start_y + int(template_height/2)
        if similarity1 < similarity:
            return -1, -1
        else:
            return center_x, center_y

    #断言
    def check_exsit(self, template_name):
        x, y = self.find_image(template_name)
        if x == -1 and y == -1:
            return False
        else:
            return True

if __name__ == '__main__':
    os.system('start /b calc.exe')
    time.sleep(5)

    match = ImageMatchByCV()
    x, y = match.find_image('add.png', similarity=0.9)
    print(x, y)